package com.example.voucher.config.util;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.voucher.biz.EasMappingBiz;
import com.example.voucher.common.TenantCodeThreadLocal;
import com.example.voucher.entity.MappingItem;

@Component
public class EasMappingHandler {

    @Autowired
    private EasMappingBiz easMappingBiz;

    public MappingItem queryEasMapping(String mappingCode, String fromDataName) {
        String tenantCode = TenantCodeThreadLocal.getTenantCode();
        List<MappingItem> list = easMappingBiz.listMappingItemByTenantCode(tenantCode);
        Map<String, Map<String, MappingItem>> easMappingMap =
            list.stream().collect(Collectors.groupingBy(MappingItem::getMappingCode,
                Collectors.toMap(MappingItem::getFromDataName, Function.identity())));
        if (easMappingMap.containsKey(mappingCode)) {
            Map<String, MappingItem> codeMap = easMappingMap.get(mappingCode);
            if (null != codeMap && codeMap.containsKey(fromDataName)) {
                MappingItem mappingItem = codeMap.get(fromDataName);
                if (null != mappingItem) {
                    return mappingItem;
                }
            }
        }
        MappingItem defaultMappingItem = new MappingItem();
        defaultMappingItem.setToDataCode(fromDataName);
        defaultMappingItem.setToDataName(fromDataName);
        return defaultMappingItem;
    };
    
    public MappingItem queryEasMappingByCode(String mappingCode, String fromDataCode) {
        String tenantCode = TenantCodeThreadLocal.getTenantCode();
        List<MappingItem> list = easMappingBiz.listMappingItemByTenantCode(tenantCode);
        Map<String, Map<String, MappingItem>> easMappingMap =
            list.stream().collect(Collectors.groupingBy(MappingItem::getMappingCode,
                Collectors.toMap(MappingItem::getFromDataCode, Function.identity())));
        if (easMappingMap.containsKey(mappingCode)) {
            Map<String, MappingItem> codeMap = easMappingMap.get(mappingCode);
            if (null != codeMap && codeMap.containsKey(fromDataCode)) {
                MappingItem mappingItem = codeMap.get(fromDataCode);
                if (null != mappingItem) {
                    return mappingItem;
                }
            }
        }
        MappingItem defaultMappingItem = new MappingItem();
        defaultMappingItem.setToDataCode(fromDataCode);
        defaultMappingItem.setToDataName(fromDataCode);
        return defaultMappingItem;
    };    

}
